package com.springboot.demo.common;


import com.springboot.demo.entity.Menu;
import com.springboot.demo.entity.Role;
import com.springboot.demo.entity.User;
import com.springboot.demo.entity.UserDetailsImpl;
import com.springboot.demo.mapper.MenuMapper;
import com.springboot.demo.mapper.RoleMapper;
import com.springboot.demo.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

@Component
@Slf4j
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    MenuService menuService;
    @Autowired
    RoleMapper roleMapper;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 将请求的url对应的角色加入到SecurityConfig中
     *
     * @param o
     * @return
     * @throws IllegalArgumentException
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //获取请求的url
        String requestUrl = ((FilterInvocation) o).getRequest().getRequestURI();
        String method = ((FilterInvocation) o).getRequest().getMethod();
        // 查询出来了每一个菜单及其对应所需要的角色
        List<Menu> menus = menuService.getAllMenus();
        //遍历资源，查找用户访问的资源
        for (Menu menu : menus) {
            //判断请求url,method与菜单角色是否匹配,兼容restful风格url
            if (antPathMatcher.match(menu.getUrl(), requestUrl) && method.equalsIgnoreCase(menu.getMethod())) {
                List<Long> menuAllRoles = menuService.getMenuAllRoles(menu.getUrl(), menu.getMethod());
                //将url匹配到的菜单所需要的所有角色加入到Security中
                if (menuAllRoles != null && !menuAllRoles.isEmpty()) {
                    String[] roleArr = new String[menuAllRoles.size()];
                    for (int i = 0; i < roleArr.length; i++) {
                        roleArr[i] = String.valueOf(menuAllRoles.get(i));
                    }
                    return SecurityConfig.createList(roleArr);
                }
            }
        }
        //没有匹配的url默认登录即可访问
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}